package com.ddc.study.feature.main.tree.detail;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

import com.ddc.study.R;
import com.ddc.study.base.MvpActivity;
import com.ddc.study.entity.Article;
import com.ddc.study.entity.MainData;
import com.ddc.study.feature.html.HtmlActivity;
import com.ddc.study.view.VerticalDecoration;

import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created on 2018/6/6.
 *
 * @author lshun
 * @version 1.0
 */
public class TreeDetailActivity extends MvpActivity<TreeDetailContract.IView, TreeDetailContract.IPresenter>
        implements TreeDetailContract.IView {
    private static final String INTENT_KEY_ID = "id";
    private static final String INTENT_KEY_TITLE = "title";

    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    @BindView(R.id.layout_load_failed)
    View mLoadFailedView;

    private final TreeDetailAdapter mAdapter = new TreeDetailAdapter();
    private int mPage;

    public static void openDetail(Context context, int id, String title) {
        Intent i = new Intent(context, TreeDetailActivity.class);
        i.putExtra(INTENT_KEY_ID, id);
        i.putExtra(INTENT_KEY_TITLE, title);
        context.startActivity(i);
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_tree_detail;
    }

    @Override
    protected TreeDetailContract.IPresenter createPresenter() {
        return new TreeDetailPresenter();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        updateTitle();

        loadData();

        mSwipeRefreshLayout.setOnRefreshListener(() -> {
            mPresenter.loadData(0, getId());
            mAdapter.setEnableLoadMore(false);
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new VerticalDecoration(this));

        mAdapter.bindToRecyclerView(mRecyclerView);
        mAdapter.setPreLoadNumber(5);
        mAdapter.setOnLoadMoreListener(() -> {
            mSwipeRefreshLayout.setEnabled(false);
            mPresenter.loadData(mPage, getId());
        }, mRecyclerView);

        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            Article article = mAdapter.getItem(position);
            if (article != null) {
                HtmlActivity.openUrl(TreeDetailActivity.this, article.getLink());
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void showData(@Nullable MainData<Article> data) {
        if (mAdapter.isLoading()) {//自动加载
            if (data == null) {
                mAdapter.loadMoreFail();
            } else {
                List<Article> articles = data.getData();
                if (articles != null && !articles.isEmpty()) {
                    mAdapter.addData(articles);
                }
                //加载成功后页码+1
                mPage++;
                //判断自动加载是否全部完成
                if (data.isDataLoadOver()) {
                    mAdapter.loadMoreEnd(true);
                } else {
                    mAdapter.loadMoreComplete();
                }
            }
            //自动加载完毕后启用下拉刷新
            mSwipeRefreshLayout.setEnabled(true);
        } else if (mSwipeRefreshLayout.isRefreshing()) {//下拉刷新
            if (data == null) {
                showToast("刷新失败");
            } else {
                mPage = 1;
                mAdapter.setNewData(data.getData());
                //判断是否已经加载完毕 防止重复加载
                if (data.isDataLoadOver()) {
                    mAdapter.loadMoreEnd(true);
                }
            }
            //隐藏下拉刷新的动画效果
            mSwipeRefreshLayout.setRefreshing(false);
            //下拉刷新完毕后启用自动加载
            mAdapter.setEnableLoadMore(true);
        }
    }

    @OnClick(R.id.layout_load_failed)
    void loadData() {
        mPresenter.loadData(mPage, getId());
        mLoadFailedView.setVisibility(View.GONE);
        if (!mSwipeRefreshLayout.isRefreshing()) mSwipeRefreshLayout.setRefreshing(true);
    }

    private int getId() {
        return getIntent().getIntExtra(INTENT_KEY_ID, -1);
    }

    private void updateTitle() {
        String title = getIntent().getStringExtra(INTENT_KEY_TITLE);
        if (title != null) setTitle(title);
    }

    private void showNormalView() {
        mLoadFailedView.setVisibility(View.GONE);
        mSwipeRefreshLayout.setVisibility(View.VISIBLE);
        mSwipeRefreshLayout.setRefreshing(false);
    }

    private void showLoadingView() {
        mLoadFailedView.setVisibility(View.GONE);
        mSwipeRefreshLayout.setVisibility(View.VISIBLE);
        mSwipeRefreshLayout.setRefreshing(true);
    }

    private void showLoadFailedView() {
        mLoadFailedView.setVisibility(View.VISIBLE);
        mSwipeRefreshLayout.setVisibility(View.GONE);
        mSwipeRefreshLayout.setRefreshing(false);
    }
}
